package com.hongxun.modules.api.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.common.utils.*;
import com.hongxun.modules.api.annotation.AuthIgnore;
import com.hongxun.modules.api.entity.*;
import com.hongxun.modules.api.service.*;
import com.hongxun.modules.bss.entity.*;
import com.hongxun.modules.bss.service.*;
import com.hongxun.modules.eys.entity.EProblemEntity;
import com.hongxun.modules.eys.service.*;
import com.hongxun.modules.sys.controller.AbstractController;
import com.hongxun.modules.sys.entity.SysUserEntity;
import com.hongxun.modules.sys.service.SysDeptService;
import com.hongxun.modules.sys.service.SysUserService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.util.TextUtils;
import org.apache.velocity.texen.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by admin on 2019/8/19.
 * 文件登录，文件数据导出，导入接口。
 */
@RestController
@RequestMapping("/fileLogin")
public class FileLoginController extends AbstractController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisUtils redisUtil;
    @Autowired
    SysDeptService sysDeptService;
    @Autowired
    BDataDictionaryService bDataDictionaryService;
    @Autowired
    BDeviceService bDeviceService;//设备
    @Autowired
    BDeviceQuantitiesService bDeviceQuantitiesService;//设备工程量
    @Autowired
    BMaterialService bMaterialService;//材料
    @Autowired
    BMaterialQuantitiesService bMaterialQuantitiesService;//材料工程量
    @Autowired
    BCrossQuantitiesService bCrossQuantitiesService;//交垮工程量
    @Autowired
    BBudgetItemService bBudgetItemService;//预算项
    @Autowired
    BBudgetStandardService bBudgetStandardService;//预算标准
    @Autowired
    BEntryCriteriaService bEntryCriteriaService;//准入条件
    @Autowired
    BOtherCostService bOtherCostService;//其他费用模板
    @Autowired
    BOtherQuantitiesService bOtherQuantitiesService;//其他工程量
    @Autowired
    BProjectApplicationService bProjectApplicationService;//申请书
    @Autowired
    BEstimateService bEstimateService;//估算简表
    @Autowired
    BPointConfigService bPointConfigService;//点位配置表

    /**
     * 项目基本信息
     */
    @Autowired
    APBaseService apBaseService;//项目
    @Autowired
    APCostService apCostService;
    @Autowired
    APCriteriaService apCriteriaService;
    @Autowired
    APEstimateService apEstimateService;
    @Autowired
    APOtherService apOtherService;
    @Autowired
    APRangeService apRangeService;
    @Autowired
    APWireService apWireService;
    /**
     * 项目点位信息
     */
    @Autowired
    DCrossCostService dCrossCostService;
    @Autowired
    DDrawLineService dDrawLineService;
    @Autowired
    DPointService dPointService;
    /**
     * 项目设备及材料信息
     */
    @Autowired
    DDeviceOldService dDeviceOldService;
    @Autowired
    DDeviceBuyService dDeviceBuyService;
    @Autowired
    DMaterialBuyService dMaterialBuyService;
    @Autowired
    DMaterialOldService dMaterialOldService;

    /**
     * 项目工程量信息
     */
    @Autowired
    DOtherCostService dOtherCostService;
    @Autowired
    DMaterialCostService dMaterialCostService;
    @Autowired
    DWorkContentService dWorkContentService;

    @Autowired
    DPictureService dPictureService;
    /**
     * 隐患
     */
    @Autowired
    EProblemService eProblemService;
    @Autowired
    EProblemexistService eProblemexistService;
    @Autowired
    EPointService ePointService;
    @Autowired
    ECrossCostService eCrossCostService;
    @Autowired
    EDrawLineService eDrawLineService;
    @Autowired
    EPBaseService epBaseService;
    @Autowired
    EPRangeService epRangeService;
    @Autowired
    EPWireService epWireService;
    @Autowired
    EDeviceBuyService eDeviceBuyService;
    @Autowired
    EDeviceOldService eDeviceOldService;
    @Autowired
    EMaterialBuyService eMaterialBuyService;
    @Autowired
    EMaterialOldService eMaterialOldService;
    @Autowired
    EWorkContentService eWorkContentService;

    @Autowired
    DMaterialModelService dMaterialModelService;
    @Autowired
    DMaterialModelItemService dMaterialModelItemService;

    @Value("${com.hongxun.IMAGEROTT}")
    private String ROOT;

    @RequestMapping(value = "/updown")
    public void updown(HttpServletResponse response) throws InterruptedException {
        setDownLoadFile( response,"filestools.rar" );
    }
    @RequestMapping(value = "/login")
    public void login(HttpServletResponse response) throws InterruptedException {
        Map<String, Object> concurrentHashMap = new ConcurrentHashMap<>();
        SysUserEntity user = getUser();
        String token = jwtUtils.generateToken(user.getUserId());
        concurrentHashMap.put("user", JSON.toJSONString(user));
        concurrentHashMap.put("token", token);
        ExecutorService executorService = Executors.newFixedThreadPool(20);//获取线程池
        CountDownLatch latch = new CountDownLatch(5);//线程计数器
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> map = new HashMap<>();
                List<BDataDictionaryEntity> bDataDictionaryEntities = bDataDictionaryService.queryList(map);
                List<BDeviceEntity> bDeviceEntities = bDeviceService.queryList(map);
                List<BMaterialEntity> bMaterialEntities = bMaterialService.queryList(map);
                List<BCrossQuantitiesEntity> bCrossQuantitiesEntities = bCrossQuantitiesService.queryList(map);
                List<BBudgetItemEntity> bBudgetItemEntities = bBudgetItemService.queryList(map);
                List<BBudgetStandardEntity> bBudgetStandardEntities = bBudgetStandardService.queryList(map);
                concurrentHashMap.put("bDataDictionaryEntities", bDataDictionaryEntities);
                concurrentHashMap.put("bDeviceEntities", bDeviceEntities);
                concurrentHashMap.put("bMaterialEntities", bMaterialEntities);
                concurrentHashMap.put("bCrossQuantitiesEntities", bCrossQuantitiesEntities);
                concurrentHashMap.put("bBudgetItemEntities", bBudgetItemEntities);
                concurrentHashMap.put("bBudgetStandardEntities", bBudgetStandardEntities);
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> map = new HashMap<>();
                List<BEntryCriteriaEntity> bEntryCriteriaEntities = bEntryCriteriaService.queryList(map);
                List<BOtherCostEntity> bOtherCostEntities = bOtherCostService.queryList(map);
                List<BOtherQuantitiesEntity> bOtherQuantitiesEntities = bOtherQuantitiesService.queryList(map);
                List<BProjectApplicationEntity> bProjectApplicationEntities = bProjectApplicationService.queryList(map);
                List<BEstimateEntity> bEstimateEntities = bEstimateService.queryList(map);
                List<BPointConfigEntity> bPointConfigEntities = bPointConfigService.queryList(map);
                List<SysUserEntity> sysUserEntities = sysUserService.queryList(map);
                concurrentHashMap.put("bEntryCriteriaEntities", bEntryCriteriaEntities);
                concurrentHashMap.put("bOtherCostEntities", bOtherCostEntities);
                concurrentHashMap.put("bOtherQuantitiesEntities", bOtherQuantitiesEntities);
                concurrentHashMap.put("bProjectApplicationEntities", bProjectApplicationEntities);
                concurrentHashMap.put("bEstimateEntities", bEstimateEntities);
                concurrentHashMap.put("bPointConfigEntities", bPointConfigEntities);
                concurrentHashMap.put("sysUserEntities", sysUserEntities);
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> map = new HashMap<>();
                List<BDeviceQuantitiesEntity> bDeviceQuantitiesEntities = bDeviceQuantitiesService.queryList(map);
                concurrentHashMap.put("bDeviceQuantitiesEntities", bDeviceQuantitiesEntities);
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> map = new HashMap<>();
                List<BMaterialQuantitiesEntity> bMaterialQuantitiesEntities = bMaterialQuantitiesService.queryList(map);
                List<EProblemEntity> eProblemEntities = eProblemService.queryList(map);
                concurrentHashMap.put("bMaterialQuantitiesEntities", bMaterialQuantitiesEntities);
                concurrentHashMap.put("eProblemEntities", eProblemEntities);
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> q = new HashMap<>();
                String filter = "d_material_model.range =  1 or create_id = " + user.getUserId();
                q.put("filterSql", filter);
                List<DMaterialModelEntity> dMaterialModelEntities1 = dMaterialModelService.queryList(q);
                List<DMaterialModelItemEntity> entities = new ArrayList<>();
                for (DMaterialModelEntity d : dMaterialModelEntities1) {
                    filter = "model_guid = '" + d.getGuid() + "'";
                    q.put("filterSql", filter);
                    List<DMaterialModelItemEntity> entities1 = dMaterialModelItemService.queryList(q);
                    entities.addAll(entities1);
                }
                concurrentHashMap.put("dMaterialModelEntities", dMaterialModelEntities1);
                concurrentHashMap.put("dMaterialModelItemEntities", entities);
                latch.countDown();
            }
        });
        latch.await();
        executorService.shutdown();
        String res = JSON.toJSONString(concurrentHashMap);
        String tel = user.getMobile();
        String dt =DateUtils.getCurrentTime(DateUtils.DATE_TIME_PATTERN_New);
        String fiename = "login_"+tel+"_"+dt+".txt";

        if (FileLoginUtils.string2File(res, ROOT +fiename)) {
            setDownLoadFile(response, fiename);


        }
    }




    private String photoFile = "";
    private String dataFile = "";
    private String pictureFile = "";
    private String dataFilezip = "";

    @RequestMapping(value = "/importProject")
    public R importProject(@RequestParam("files") MultipartFile[] files) throws InterruptedException {
        photoFile = ROOT + "photo.txt";
        dataFile = ROOT + "data.txt";
        pictureFile = ROOT + "photo.zip";
        dataFilezip = ROOT + "data.zip";
        //判断file数组不能为空并且长度大于0
        int length = files.length;
        if (files == null || length != 2 || !isTrueFiles(files)) {
            return R.error("文件数据错误。两个文件，分别是:[data.zip] [photo.zip]。!");
        } else {//先存储文件。。。。
            try {
                //循环获取file数组中得文件
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    String filename = file.getOriginalFilename();
                    if (filename.equals("data.zip")) {
                        File data = new File(dataFilezip);
                        if (data.exists()) data.delete();
                        FileUtils.copyInputStreamToFile(file.getInputStream(), data);
                        unzip(data);
                    } else {
                        File picture = new File(pictureFile);
                        if (picture.exists()) picture.delete();
                        FileUtils.copyInputStreamToFile(file.getInputStream(), picture);
                    }
                }
                ExecutorService executorService = Executors.newFixedThreadPool(20);//获取线程池
                CountDownLatch latch = new CountDownLatch(2);//线程计数器
                Map<String, Object> map = new ConcurrentHashMap<>();
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        String data = FileLoginUtils.file2String(dataFile);
                        map.put("data", JSONObject.parseObject(data));
                        latch.countDown();
                    }
                });
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        String photo = FileLoginUtils.file2String(photoFile);
                        map.put("photo", JSON.parseArray(photo, DPictureEntity.class));
                        latch.countDown();
                    }
                });
                latch.await();
                executorService.shutdown();
                setPhotoData((List<DPictureEntity>) map.get("photo"));
                setData((JSONObject) map.get("data"));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return R.ok();
    }

    //处理点位数据。
    void setData(JSONObject map) {
        try {
            ExecutorService executorService = Executors.newFixedThreadPool(20);//获取线程池
            CountDownLatch latch = new CountDownLatch(4);//线程计数器
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    APBaseEntity apBaseEntity = JSON.parseObject(map.get("apBaseEntity").toString(), APBaseEntity.class);
                    APBaseEntity a = apBaseService.queryObject(apBaseEntity.getGuid());
                    if (a != null) {
                        if (a.getPBBookname() != null && !a.getPBBookname().equals("")) {
                            apBaseEntity.setPBBookname(a.getPBBookname());
                        } else {
                            apBaseEntity.setPBBookname(apBaseEntity.getPBName() + "项目申请书");
                        }
                    } else {
                        apBaseEntity.setPBBookname(apBaseEntity.getPBName() + "项目申请书");
                    }
                    List<APCostEntity> apCostEntities = JSON.parseArray(map.get("apCostEntities").toString(), APCostEntity.class);
                    List<APCriteriaEntity> apCriteriaEntities = JSON.parseArray(map.get("apCriteriaEntities").toString(), APCriteriaEntity.class);
                    List<APEstimateEntity> apEstimateEntities = JSON.parseArray(map.get("apEstimateEntities").toString(), APEstimateEntity.class);
                    List<APOtherEntity> apOtherEntities = JSON.parseArray(map.get("apOtherEntities").toString(), APOtherEntity.class);
                    List<APRangeEntity> apRangeEntities = JSON.parseArray(map.get("apRangeEntities").toString(), APRangeEntity.class);
                    List<APWireEntity> apWireEntities = JSON.parseArray(map.get("apWireEntities").toString(), APWireEntity.class);
                    List<DPointEntity> dPointEntities = JSON.parseArray(map.get("dPointEntities").toString(), DPointEntity.class);
                    if (dPointEntities.size() > 0) {
                         apBaseEntity.setPBLatitude(dPointEntities.get(0).getPPInputlatitude());
                         apBaseEntity.setPBLongitude(dPointEntities.get(0).getPPInputlongitude());
                    }

                    apBaseService.insertOrReplaceOrDelete(apBaseEntity);
                    apCostService.insertOrReplaceOrDelete(apCostEntities);
                    apCriteriaService.insertOrReplaceOrDelete(apCriteriaEntities);
                    apEstimateService.insertOrReplaceOrDelete(apEstimateEntities);
                    apOtherService.insertOrReplaceOrDelete(apOtherEntities);
                    apRangeService.insertOrReplaceOrDelete(apRangeEntities);
                    apWireService.insertOrReplaceOrDelete(apWireEntities);

                    latch.countDown();
                }
            });
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    List<DCrossCostEntity> dCrossCostEntities = JSON.parseArray(map.get("dCrossCostEntities").toString(), DCrossCostEntity.class);
                    List<DDrawLineEntity> dDrawLineEntities = JSON.parseArray(map.get("dDrawLineEntities").toString(), DDrawLineEntity.class);
                    List<DPointEntity> dPointEntities = JSON.parseArray(map.get("dPointEntities").toString(), DPointEntity.class);
                    dCrossCostService.insertOrReplaceOrDelete(dCrossCostEntities);
                    dDrawLineService.insertOrReplaceOrDelete(dDrawLineEntities);
                    dPointService.insertOrReplaceOrDelete(dPointEntities);
                    latch.countDown();
                }
            });
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    List<DDeviceBuyEntity> dDeviceBuyEntities = JSON.parseArray(map.get("dDeviceBuyEntities").toString(), DDeviceBuyEntity.class);
                    List<DDeviceOldEntity> dDeviceOldEntities = JSON.parseArray(map.get("dDeviceOldEntities").toString(), DDeviceOldEntity.class);
                    List<DMaterialBuyEntity> dMaterialBuyEntities = JSON.parseArray(map.get("dMaterialBuyEntities").toString(), DMaterialBuyEntity.class);
                    List<DMaterialOldEntity> dMaterialOldEntities = JSON.parseArray(map.get("dMaterialOldEntities").toString(), DMaterialOldEntity.class);
                    dDeviceBuyService.insertOrReplaceOrDelete(dDeviceBuyEntities);
                    dDeviceOldService.insertOrReplaceOrDelete(dDeviceOldEntities);
                    dMaterialBuyService.insertOrReplaceOrDelete(dMaterialBuyEntities);
                    dMaterialOldService.insertOrReplaceOrDelete(dMaterialOldEntities);
                    latch.countDown();
                }
            });
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    List<DOtherCostEntity> dOtherCostEntities = JSON.parseArray(map.get("dOtherCostEntities").toString(), DOtherCostEntity.class);
                    List<DMaterialCostEntity> dMaterialCostEntities = JSON.parseArray(map.get("dMaterialCostEntities").toString(), DMaterialCostEntity.class);
                    List<DWorkContentEntity> dWorkContentEntities = JSON.parseArray(map.get("dWorkContentEntities").toString(), DWorkContentEntity.class);
                    dOtherCostService.insertOrReplaceOrDelete(dOtherCostEntities);
                    dMaterialCostService.insertOrReplaceOrDelete(dMaterialCostEntities);
                    dWorkContentService.insertOrReplaceOrDelete(dWorkContentEntities);
                    latch.countDown();
                }
            });
            latch.await();
            executorService.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //处理图片数据信息。
    void setPhotoData(List<DPictureEntity> pictureEntities) {
        try {
            if(pictureEntities.size()>0) {
                setFile(pictureEntities);
                dPictureService.insertOrReplaceOrDelete(pictureEntities);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断文件数据是否正确。
    boolean isTrueFiles(MultipartFile[] files) {
        List<String> list = new ArrayList<>();
        //list.add("photo.txt");
        list.add("data.zip");
        list.add("photo.zip");
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String filename = file.getOriginalFilename();
            if (list.contains(filename)) {
                list.remove(filename);
            }
        }
        return list.size() == 0;
    }

    private void setFile(List<DPictureEntity> bean)
            throws IOException {
        unzip(new File(pictureFile), bean);

    }

    boolean setBeanName(List<DPictureEntity> bean, String oldName, String newName) {
        for (DPictureEntity d : bean) {
            if (d.getPName().equals(oldName)) {//如果有，则先判断图片是否已经存在。
                if (!TextUtils.isEmpty(d.getPServeraddress()) && new File(ROOT + d.getPServeraddress()).exists()) {
                    return true;
                } else {
                    d.setPServeraddress(newName);
                }
            }
        }
        return false;
    }

    void unzip(File file, List<DPictureEntity> bean) throws IOException {
        ZipFile zipFile = new ZipFile(file, Charset.forName("UTF-8"));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        ExecutorService executorService = Executors.newFixedThreadPool(20);//获取线程池

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    while (entries.hasMoreElements()) {
                        ZipEntry zipEntry = entries.nextElement();
                        long l = System.currentTimeMillis();
                        String fileName = l + zipEntry.getName();
                        if (!setBeanName(bean, zipEntry.getName(), fileName)) {
                            File targetFile = new File(new File(ROOT), fileName);
                            if (!zipEntry.isDirectory()) {
                                try {
                                    InputStream input = zipFile.getInputStream(zipEntry);
                                    FileUtils.copyInputStreamToFile(input, targetFile);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                targetFile.mkdirs();
                            }
                        }
                    }
                }
            });


        executorService.shutdown();
        while (true) {
            if (executorService.isTerminated()) {
                IOUtils.closeQuietly(zipFile);
                break;
            }
        }
    }

    void unzip(File file) throws IOException {
        ZipFile zipFile = new ZipFile(file, Charset.forName("UTF-8"));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        ExecutorService executorService = Executors.newFixedThreadPool(20);//获取线程池

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (entries.hasMoreElements()) {
                    ZipEntry zipEntry = entries.nextElement();
                    String fileName =  zipEntry.getName();
                     File targetFile = new File(new File(ROOT), fileName);
                    if (!zipEntry.isDirectory()) {
                        try {
                            InputStream input = zipFile.getInputStream(zipEntry);
                            FileUtils.copyInputStreamToFile(input, targetFile);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        targetFile.mkdirs();
                    }

                }
            }
        });


        executorService.shutdown();
        while (true) {
            if (executorService.isTerminated()) {
                IOUtils.closeQuietly(zipFile);
                break;
            }
        }
    }






    //下载项目文件，暂未下载图片文件。后期考虑
    @RequestMapping(value = "/exportProject")
    public void exportProject(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        String uuid = params.get("uuid").toString();
        Map<String, Object> map = new HashMap<>();
        String filter = "p_guid = '" + uuid + "'";
        map.put("filterSql", filter);
        APBaseEntity apBaseEntity = apBaseService.queryObject(uuid);
        List<APCostEntity> apCostEntities = apCostService.queryList(map);
        List<APCriteriaEntity> apCriteriaEntities = apCriteriaService.queryList(map);
        List<APEstimateEntity> apEstimateEntities = apEstimateService.queryList(map);
        List<APOtherEntity> apOtherEntities = apOtherService.queryList(map);
        List<APRangeEntity> apRangeEntities = apRangeService.queryList(map);
        List<APWireEntity> apWireEntities = apWireService.queryList(map);
        List<DCrossCostEntity> dCrossCostEntities = dCrossCostService.queryList(map);
        List<DDeviceBuyEntity> dDeviceBuyEntities = dDeviceBuyService.queryList(map);
        List<DDeviceOldEntity> dDeviceOldEntities = dDeviceOldService.queryList(map);
        List<DDrawLineEntity> dDrawLineEntities = dDrawLineService.queryList(map);
        List<DMaterialBuyEntity> dMaterialBuyEntities = dMaterialBuyService.queryList(map);
        List<DMaterialCostEntity> dMaterialCostEntities = dMaterialCostService.queryList(map);
        List<DMaterialOldEntity> dMaterialOldEntities = dMaterialOldService.queryList(map);
        List<DOtherCostEntity> dOtherCostEntities = dOtherCostService.queryList(map);
        List<DPointEntity> dPointEntities = dPointService.queryList(map);
        List<DWorkContentEntity> dWorkContentEntities = dWorkContentService.queryList(map);
        filter += "and p_status = '储备'";
        map.put("filterSql", filter);
        List<DPictureEntity> dPictureEntities = dPictureService.queryList(map);
        map.put("apBaseEntity", JSON.toJSONString(apBaseEntity));
        map.put("apCostEntities", JSON.toJSONString(apCostEntities));
        map.put("apCriteriaEntities", JSON.toJSONString(apCriteriaEntities));
        map.put("apEstimateEntities", JSON.toJSONString(apEstimateEntities));
        map.put("apOtherEntities", JSON.toJSONString(apOtherEntities));
        map.put("apRangeEntities", JSON.toJSONString(apRangeEntities));
        map.put("apWireEntities", JSON.toJSONString(apWireEntities));
        map.put("dCrossCostEntities", JSON.toJSONString(dCrossCostEntities));
        map.put("dDeviceBuyEntities", JSON.toJSONString(dDeviceBuyEntities));
        map.put("dDeviceOldEntities", JSON.toJSONString(dDeviceOldEntities));
        map.put("dDrawLineEntities", JSON.toJSONString(dDrawLineEntities));
        map.put("dMaterialBuyEntities", JSON.toJSONString(dMaterialBuyEntities));
        map.put("dMaterialCostEntities", JSON.toJSONString(dMaterialCostEntities));
        map.put("dMaterialOldEntities", JSON.toJSONString(dMaterialOldEntities));
        map.put("dOtherCostEntities", JSON.toJSONString(dOtherCostEntities));
        map.put("dPictureEntities", JSON.toJSONString(dPictureEntities));
        map.put("dPointEntities", JSON.toJSONString(dPointEntities));
        map.put("dWorkContentEntities", JSON.toJSONString(dWorkContentEntities));
        String res = JSON.toJSONString(map);
        String dt =DateUtils.getCurrentTime(DateUtils.DATE_TIME_PATTERN_New);
        String fiename = "point_"+apBaseEntity.getPBName()+"_"+dt+".txt";
        if (FileLoginUtils.string2File(res, ROOT +fiename)) {
            setDownLoadFile(response, fiename);
        }
    }

    void setDownLoadFile(HttpServletResponse response, String fileName) {
        try {
            // 读到流中
            InputStream inStream = new FileInputStream(ROOT + fileName);// 文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName ,"UTF-8") + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
